package com.triones.yjj.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.StringUtils;
import com.triones.framework.common.util.StringUtil;
import com.triones.yjj.entity.*;
import com.triones.yjj.entity.bo.*;
import com.triones.yjj.entity.vo.*;
import com.triones.yjj.mapper.*;
import com.triones.yjj.service.MemberBrowseService;
import com.triones.yjj.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 客户管理 service 业务实现
 *
 * @Author: triones
 */
@Service
@RequiredArgsConstructor
public class MemberBrowseServiceImpl implements MemberBrowseService {

    private final MemberBrowseMapper memberBrowseMapper;

    private final MemberMapper memberMapper;

    private final MemberBrowseRecordMapper memberBrowseRecordMapper;


    public Long browseStart(MemberBrowseStartParams params, MemberDetailVO memberDetailVO) {
        LambdaQueryWrapper<MemberBrowseDO> wrapper = Wrappers.lambdaQuery(MemberBrowseDO.class);
        wrapper.eq(MemberBrowseDO::getMemberId,memberDetailVO.getId());
        wrapper.eq(MemberBrowseDO::getUserId,memberDetailVO.getUserId());
        wrapper.eq(MemberBrowseDO::getProductId,params.getActivityId());
        wrapper.eq(MemberBrowseDO::getInviteStaffId,params.getInviteStaffId());
        wrapper.eq(MemberBrowseDO::getStaffWxUserId,params.getStaffWxUserId());
        wrapper.last(" limit 1");
        MemberBrowseDO memberBrowseDO =  memberBrowseMapper.selectOne(wrapper);
        if(ObjectUtil.isEmpty(memberBrowseDO)){
            memberBrowseDO = new MemberBrowseDO();
            memberBrowseDO.setMemberId(memberDetailVO.getId());
            memberBrowseDO.setMemberWxUserId(memberDetailVO.getWxUserId());
            memberBrowseDO.setProductId(params.getActivityId());
            if(StringUtils.isEmpty(memberDetailVO.getMobile())){
                memberBrowseDO.setMemberStatus("2");//客户状态 1：已留手机号、2仅浏览客户
                memberBrowseDO.setRemainMobile(memberDetailVO.getMobile());//是否留下手机号
            }else{
                memberBrowseDO.setMemberStatus("1");//客户状态 1：已留手机号、2仅浏览客户
            }
            memberBrowseDO.setProductType(1);//产品类型
            memberBrowseDO.setBrowseNumber(1);
            memberBrowseDO.setBrowseTimeLength(0);
            memberBrowseDO.setBrowseRatio(0);//浏览完整度
            memberBrowseDO.setLatelyAccessTime(DateUtil.getDateTimeString());//最近浏览时间
            memberBrowseDO.setInviteStaffId(params.getInviteStaffId());//邀请员工Id
            memberBrowseDO.setStaffWxUserId(params.getStaffWxUserId());//员工微信用户id
            memberBrowseDO.setIsClickEnroll(2);//是否点击过报名（1：已点、2：未点）
            memberBrowseDO.setEnrollStatus(2);//报名状态 未报名
            memberBrowseDO.setUserId(memberDetailVO.getUserId());//系统用户
            memberBrowseMapper.insert(memberBrowseDO);
        }else{
            //浏览+1
            UpdateChainWrapper<MemberBrowseDO> wrapperOrder = new UpdateChainWrapper<>(memberBrowseMapper);
            wrapperOrder.setSql(" browse_number=browse_number+1 ");
//            wrapperOrder.set("invite_staff_id",params.getInviteStaffId());
//            wrapperOrder.set("staff_wx_user_id",params.getInviteStaffId());
            wrapperOrder.eq("id",memberBrowseDO.getId());
            wrapperOrder.update();
        }

        //保存浏览记录
        MemberBrowseRecordDO memberBrowseRecordDO = new MemberBrowseRecordDO();
        memberBrowseRecordDO.setBrowseId(memberBrowseDO.getId());
        memberBrowseRecordDO.setMemberId(memberDetailVO.getId());
        memberBrowseRecordDO.setMemberWxUserId(memberDetailVO.getWxUserId());
        memberBrowseRecordDO.setEntryTime(DateUtil.getDateTimeString());
        memberBrowseRecordDO.setUserId(memberDetailVO.getUserId());
        memberBrowseRecordMapper.insert(memberBrowseRecordDO);

        return memberBrowseRecordDO.getId();
    }

    public R<T> browseEnd(MemberBrowseEndParams params, MemberDetailVO memberDetailVO) {
        MemberBrowseRecordDO memberBrowseRecordDO = memberBrowseRecordMapper.selectById(params.getMemberBrowseRecordId());
        if(ObjectUtil.isNotEmpty(memberBrowseRecordDO)){
            MemberBrowseDO memberBrowseDO =   memberBrowseMapper.selectById(memberBrowseRecordDO.getBrowseId());
            if(ObjectUtil.isNotEmpty(memberBrowseDO)){
                LambdaUpdateWrapper<MemberBrowseDO> updateWrapper1 = Wrappers.lambdaUpdate(MemberBrowseDO.class);
                if (memberBrowseDO.getIsClickEnroll() != 1) {
                    updateWrapper1.set(MemberBrowseDO::getIsClickEnroll,params.getIsClickEnroll());
                }
                updateWrapper1.set(MemberBrowseDO::getLatelyAccessTime,DateUtil.getDateTimeString());
                updateWrapper1.set(MemberBrowseDO::getBrowseTimeLength, NumberUtil.add(memberBrowseDO.getBrowseTimeLength(),params.getBrowseTimeLength()));
                if(params.getBrowseRatio().intValue()>memberBrowseDO.getBrowseRatio().intValue()){
                    updateWrapper1.set(MemberBrowseDO::getBrowseRatio,params.getBrowseRatio());
                }
                updateWrapper1.eq(MemberBrowseDO::getId,memberBrowseDO.getId());
                memberBrowseMapper.update(memberBrowseDO,updateWrapper1);

                LambdaUpdateWrapper<MemberBrowseRecordDO> updateWrapper = Wrappers.lambdaUpdate(MemberBrowseRecordDO.class);
                updateWrapper.set(MemberBrowseRecordDO::getQuitTime,DateUtil.getDateTimeString());
                //updateWrapper.set(MemberBrowseRecordDO::getTravel,params.getTravel());
                updateWrapper.set(MemberBrowseRecordDO::getBrowseType,params.getBrowseType());
                updateWrapper.set(MemberBrowseRecordDO::getBrowseTime,params.getBrowseTimeLength());
                updateWrapper.set(MemberBrowseRecordDO::getBrowseRatio,params.getBrowseRatio());
                updateWrapper.eq(MemberBrowseRecordDO::getId,memberBrowseRecordDO.getId());
                memberBrowseRecordMapper.update(memberBrowseRecordDO,updateWrapper);
                return  R.ok("成功");
            }else{
                return  R.fail("浏览不存在");
            }
        }else{
            return  R.fail("浏览记录不存在");
        }
    }


    public void saveBrowse(Long activityId,StaffVO staffVO, MemberDetailVO memberDetailVO,String browseType) {
        LambdaQueryWrapper<MemberBrowseDO> wrapper = Wrappers.lambdaQuery(MemberBrowseDO.class);
        wrapper.eq(MemberBrowseDO::getMemberId,memberDetailVO.getId());
        wrapper.eq(MemberBrowseDO::getUserId,memberDetailVO.getUserId());
        wrapper.eq(MemberBrowseDO::getProductId,activityId);
        if(ObjectUtil.isNotEmpty(staffVO)){
            wrapper.eq(MemberBrowseDO::getInviteStaffId,staffVO.getId());
            wrapper.eq(MemberBrowseDO::getStaffWxUserId,staffVO.getWxUserId());
        }else{
            wrapper.eq(MemberBrowseDO::getInviteStaffId,0l);
            wrapper.eq(MemberBrowseDO::getStaffWxUserId,0l);
        }
        wrapper.last(" limit 1");
        MemberBrowseDO memberBrowseDO =  memberBrowseMapper.selectOne(wrapper);
        String datetime = DateUtil.getDateTimeString();
        if(ObjectUtil.isEmpty(memberBrowseDO)){
            memberBrowseDO = new MemberBrowseDO();
            memberBrowseDO.setMemberId(memberDetailVO.getId());
            memberBrowseDO.setMemberWxUserId(memberDetailVO.getWxUserId());
            memberBrowseDO.setProductId(activityId);
            if(StringUtils.isEmpty(memberDetailVO.getMobile())){
                memberBrowseDO.setMemberStatus("2");//客户状态 1：已留手机号、2仅浏览客户
                memberBrowseDO.setRemainMobile(memberDetailVO.getMobile());//是否留下手机号
            }else{
                memberBrowseDO.setMemberStatus("1");//客户状态 1：已留手机号、2仅浏览客户
            }
            memberBrowseDO.setProductType(1);//产品类型  1活动 2商品
            memberBrowseDO.setBrowseNumber(1);
            memberBrowseDO.setBrowseTimeLength(0);
            memberBrowseDO.setBrowseRatio(0);//浏览完整度
            memberBrowseDO.setLatelyAccessTime(datetime);//最近浏览时间
            if(ObjectUtil.isEmpty(staffVO)){
                memberBrowseDO.setInviteStaffId(0l);//邀请员工Id
                memberBrowseDO.setStaffWxUserId(0l);//员工微信用户id
            }else{
                memberBrowseDO.setInviteStaffId(staffVO.getId());//邀请员工Id
                memberBrowseDO.setStaffWxUserId(staffVO.getWxUserId());//员工微信用户id
            }

            memberBrowseDO.setIsClickEnroll(2);//是否点击过报名（1：已点、2：未点）
            memberBrowseDO.setEnrollStatus(2);//报名状态
            memberBrowseDO.setUserId(memberDetailVO.getUserId());//系统用户
            memberBrowseMapper.insert(memberBrowseDO);
        }else{
            //浏览+1
            UpdateChainWrapper<MemberBrowseDO> wrapperOrder = new UpdateChainWrapper<>(memberBrowseMapper);
            wrapperOrder.setSql(" browse_number=browse_number+1 ");
            wrapperOrder.eq("id",memberBrowseDO.getId());
            wrapperOrder.update();
        }

        //保存浏览记录
        MemberBrowseRecordDO memberBrowseRecordDO = new MemberBrowseRecordDO();
        memberBrowseRecordDO.setBrowseId(memberBrowseDO.getId());
        memberBrowseRecordDO.setMemberId(memberDetailVO.getId());
        memberBrowseRecordDO.setMemberWxUserId(memberDetailVO.getWxUserId());
        memberBrowseRecordDO.setEntryTime(datetime);
        memberBrowseRecordDO.setQuitTime(datetime);
        String travel = "";
        if("share".equals(browseType)){
            travel = "该客户分享了你的活动";
        }
        if("enroll".equals(browseType)){
            travel = "该客户已报名";
        }
        memberBrowseRecordDO.setTravel(travel);
        memberBrowseRecordDO.setBrowseType(browseType);
        memberBrowseRecordDO.setUserId(memberDetailVO.getUserId());
        memberBrowseRecordMapper.insert(memberBrowseRecordDO);
    }


    public Long visitCount(WxVisitParams params) {
       return memberBrowseRecordMapper.getVisitCount(params);
    }

    public TableDataInfo<WxStaffMemberBrowseVO> getVisitList(WxVisitSearchParams params, PageQuery pageQuery) {
        Page<WxStaffMemberBrowseVO> result = null;
        if(params.getTodayData().intValue()==1){
            result = memberBrowseMapper.getTodayVisitList(pageQuery.build(), params);
        }else{
            QueryWrapper<MemberBrowseDO> wrapper = new QueryWrapper<>();
            wrapper.eq("a.invite_staff_id",params.getStaffId());
            wrapper.eq("a.product_id",params.getActivityId());
            wrapper.eq("a.user_id",params.getUserId());
            wrapper.isNotNull(ObjectUtil.isNotNull(params.getHasPhone())&&params.getHasPhone().intValue()==1,"d.mobile");
            wrapper.eq(ObjectUtil.isNotNull(params.getHasApply())&&params.getHasApply().intValue()==1,"a.enroll_status",1);
            result = memberBrowseMapper.getAllVisitList(pageQuery.build(), wrapper);
        }
        return TableDataInfo.build(result);
    }
}
